<?php
class Order_Service_Order {
	/* public static $processStatus = array (
		0 => '未处理',
		1 => '待下架',
		2 => '下架中',
		3 => '已下架',
		4 => '待发货',
		5 => '已发货',
		6 => '已完成',

		
	);

	public static $orderStatus = array (
		0 => '删除',
		1 => '草稿',
		2 => '已确认',
		3 => '已提交',
		4 => 'Abnormal',
		5 => '已发货',
		6 => '已完成',

		
	);
	//定义订单类型
	public static $orderType = array (
		"0" => "一票一件",
// 		"1" => "单个SKU",
		"2" => "多个SKU"
	); */
	
	public static function getProcessStatus($status){
	    $lang = Zend_Registry::get('lang');
        $processStatus = array(
                0 => $lang['process_not_deal'],
                1 => $lang['process_wait_pickup'],
                2 => $lang['process_pickuping'],
                3 => $lang['process_pickuped'],
                4 => $lang['process_wait_ship'],
                5 => $lang['process_shiped'],
                6 => $lang['process_finish'],
        )
        ;
        return $processStatus[$status];
    }

    public static function getAllProcessStatus(){
        $lang = Zend_Registry::get('lang');
        $processStatus = array(
                0 => $lang['process_not_deal'],
                1 => $lang['process_wait_pickup'],
                2 => $lang['process_pickuping'],
                3 => $lang['process_pickuped'],
                4 => $lang['process_wait_ship'],
                5 => $lang['process_shiped'],
                6 => $lang['process_finish'],
        )
        ;
        return $processStatus;
    }
    public static function getAllOrderStatus(){
        $lang = Zend_Registry::get('lang');
         $orderStatus = array(
                0 => $lang['order_delete'],
                1 => $lang['order_draft'],
                2 => $lang['order_confirm'],
                3 => $lang['order_submit'],
                99 => $lang['order_abnormal'],
                5 => $lang['order_shiped'],
                6 => $lang['order_finish'],
        );
        return $orderStatus;
    }
	public static function getOrderStatus($status){
	    $lang = Zend_Registry::get('lang');
        $orderStatus = array(
                0 => $lang['order_delete'],
                1 => $lang['order_draft'],
                2 => $lang['order_confirm'],
                3 => $lang['order_submit'],
                99 => $lang['order_abnormal'],
                5 => $lang['order_shiped'],
                6 => $lang['order_finish'],
        );
        return $orderStatus[$status];
    }
	

	public static function getOrderType($type){
	    $lang = Zend_Registry::get('lang');
        $orderType = array(
                "0" => $lang['one_piece'],
                // "1" => "单个SKU",
                "2" => $lang['more_than_one_piece']
        );
        return $orderType[$type];
    }
    public static function getAllOrderType(){
        $lang = Zend_Registry::get('lang');
        $orderType = array(
                "0" => $lang['one_piece'],
                // "1" => "单个SKU",
                "2" => $lang['more_than_one_piece']
        );
        return $orderType;
    }
	public static function getByCondition($condition = array (), $type = '*', $order = array (
		'order_id'
	), $pageSize = 0, $page = 1) {
		$obj = new Order_Model_Order();
		$rows = $obj->getByCondition($condition, $type, $order, $pageSize, $page);
		return $rows;
	}
	
	public static function getStopByCondition($condition = array (), $type = '*', $order = array (
			'order_id'
	), $pageSize = 0, $page = 1) {
		$obj = new Order_Model_Order();
		$rows = $obj->getStopByCondition($condition, $type, $order, $pageSize, $page);
		return $rows;
	}
	
	public static function getByfield($field, $value) {
		$obj = new Order_Model_Order();
		$rows = $obj->getByfield($field, $value);
		if (!empty ($rows)) {
			$rows = $rows->toArray();
		}
		return $rows;
	}

	public static function getByOrdersCode($order_code) {
		$obj = new Order_Model_Order();
		$rows = $obj->getByOrdersCode($order_code);
		if (!empty ($rows)) {
			$rows = $rows->toArray();
		}
		return $rows;
	}

	public static function getById($t_id) {
		$obj = new Order_Model_Order();
		$rows = $obj->getById($t_id);
		if (!empty ($rows)) {
			$rows = $rows->toArray();
		}
		return $rows;
	}

	public static function create($row) {
		$obj = new Order_Model_Order();
		return $obj->create($row);
	}
	/**
	*按订单ID更新
	*/
	public static function update($row, $t_id) {
		$obj = new Order_Model_Order();
		return $obj->update($row, $t_id);
	}
	/**
	*按订单序列号更新
	*/
	public static function updateByOrdersCode($row, $orders_code = '') {
		$obj = new Order_Model_Order();
		return $obj->updateByOrdersCode($row, $orders_code);
	}
	
	/**
	 *多条订单ID更新
	 */
	public static function updateByOrdersIds($row, $orderIds = '') {
		$obj = new Order_Model_Order();
		return $obj->updateByOrdersIds($row, $orderIds);
	}
	
	
	public static function getByOrdersIds($orderIds = '0') {
		$obj = new Order_Model_Order();
		return $obj->getByOrdersIds($orderIds);
	}
	
	
	public static function getByOrderCodesAllIn($orderCodes = '0') {
		$obj = new Order_Model_Order();
		return $obj->getByOrderCodesAllIn($orderCodes);
	}

	/**
	*按订单序列号更新订单物品总价值
	*return int 更新后的订单物品总价值
	*/
	public static function updateOrderMoney($orders_code = '') {
		$proRow = Order_Service_Product :: getByCondition(array (
			'orders_code' => $orders_code
		));
		$subtotal = 0; //订单总金额
		if (!empty ($proRow)) {
			foreach ($proRow as $key => $value) {
				$subtotal += $value['op_quantity'] * $value['op_unit_price']; //产品总价
			}
		}
		//更新订单物品总价值
		$update = array (
			'parcel_declared_value' => $subtotal,
			
		);
		$rows = self :: updateByOrdersCode($update, $orders_code);
		return $subtotal;
	}
	
	/**
	*根据状态码获得状态描述
	*return String
	*/

	public static function getIP() {
		$ip = $_SERVER['REMOTE_ADDR'];
		return $ip;
	}

	/*
	 * 批量提交订单到物流系统
	 */
	public static function orderBatchSubmit() {
		$condition = array("orders_status"=>3,"process_status"=>1,"import_status"=>'0');
		$pageSize = 100;
		$page = 1;
		$orders = Order_Service_Order::getByCondition($condition,'*',null,$pageSize,$page);
		$result = array();
		$orderModel= new Order_Model_Order();
		while(count($orders)){
			foreach($orders as $order){
				echo $order['orders_code']."\n";
				$import_status=0;
				$obj = new Order_Model_OrderShip();
				$Condition=array(
						'os_status'=>2,
						'orders_code'=>$order['orders_code'],
				);
				$ordership = $obj->getByCondition($Condition,'*');
				if(!empty($ordership)){
					$import_status=1;
					$orderModel->updateByOrdersCode(array('import_status'=>$import_status),$order['orders_code']);
					$result[]=array(
						'orders_code'=>$order['orders_code'],
						'msg'=>' Existing '.$ordership[0]['tracking_number'],
					);
					continue;
				}
				$obj = new Order_Service_OrderProccess($order['orders_code']);
				$create =  $obj->createIshipOrder();
				if($create){
					$import_status=1;
					$result[]=array(
						'orders_code'=>$order['orders_code'],
						'msg'=>$obj->_shipOrder,
					);
				}else{
					$import_status=2;
					$result[]=array(
						'orders_code'=>$order['orders_code'],
						'msg'=>$obj->_error,
					);
					$addRow=array(
						'orders_code'=>$order['orders_code'],
						'osh_type'=>'Process',
						'osh_statu'=>3,
						'osh_remark'=>'auto run orderBatchSubmit',
						'osh_comments'=>$obj->_error,
						'osh_create_date'=>date("Y-m-d:H:i:s"),
					);
					Order_Service_History::create($addRow);
				}
				$orderModel->updateByOrdersCode(array('import_status'=>$import_status),$order['orders_code']);
			}
			unset($orders);
			//$page ++;
			$orders = Order_Service_Order::getByCondition($condition,'*',null,$pageSize,$page);
		}
		return $result;
	}
	
	
	/*
	 * 批量更新物流系统订单重量
	 */
	public static function orderShippingUpdate() {
		$condition = array("orders_status"=>5,"process_status"=>5,"import_status"=>'1');
		$pageSize = 100;
		$page = 1;
		$orders = Order_Service_Order::getByCondition($condition,'*',null,$pageSize,$page);
		$result = array();
		while(count($orders)){
			foreach($orders as $order){
				//排除测试帐号
				if($order['customer_id']=='A0366'){
					continue;
				}
				echo $order['orders_code']."\n";
				$obj = new Order_Service_OrderProccess($order['orders_code']);
				$update =  $obj->updateIshipOrder();
				if($update){
					$result[]=array(
						'orders_code'=>$order['orders_code'],
						'msg'=>'Update Success '.date("Y-m-d:H:i:s"),
					);
				}else{
					$result[]=array(
						'orders_code'=>$order['orders_code'],
						'msg'=>$obj->_error,
					);
					$addRow=array(
						'orders_code'=>$order['orders_code'],
						'osh_type'=>'Revise',
						'osh_statu'=>3,
						'osh_remark'=>'auto run orderShippingUpdate',
						'osh_comments'=>$obj->_error,
						'osh_create_date'=>date("Y-m-d:H:i:s"),
					);
					//Order_Service_History::create($addRow);
				}
			}
			unset($orders);
			//$page ++;
			$orders = Order_Service_Order::getByCondition($condition,'*',null,$pageSize,$page);
		}	
		
		return $result;
	}
	
	/*
	 * 创建物流系统订单
	*/
	public static function createShippingCode($ordersCodes) {
		$result = array();
		$orderModel= new Order_Model_Order();
		foreach($ordersCodes as $orders_code){			
			$import_status=0;
			$obj = new Order_Model_OrderShip();
			$Condition=array(
					'os_status'=>2,
					'orders_code'=>$orders_code,
			);
			$ordership = $obj->getByCondition($Condition,'*');
			if(!empty($ordership)){
				$import_status=1;
				$orderModel->updateByOrdersCode(array('import_status'=>$import_status),$orders_code);
				$result[]=array(
						'orders_code'=>$orders_code,
						'msg'=>$orders_code.' Existing '.$ordership[0]['tracking_number'],
				);
				continue;
			}
			
			$obj = new Order_Service_OrderProccess($orders_code);
			$create =  $obj->createIshipOrder();
			if($create){
				$import_status=1;
				$result[]=array(
						'orders_code'=>$orders_code,
						'msg'=>$orders_code." --> ".$obj->_shipOrder,
				);
			}else{
				$import_status=2;
				$result[]=array(
						'orders_code'=>$orders_code,
						'msg'=>$orders_code." Error:".$obj->_error,
				);
				$addRow=array(
						'orders_code'=>$orders_code,
						'osh_type'=>'Process',
						'osh_statu'=>3,
						'osh_remark'=>'auto run orderBatchSubmit',
						'osh_comments'=>$obj->_error,
						'osh_create_date'=>date("Y-m-d:H:i:s"),
				);
				//Order_Service_History::create($addRow);
			}
			$orderModel= new Order_Model_Order();
			$orderModel->updateByOrdersCode(array('import_status'=>$import_status),$orders_code);
		}
		return $result;
	}
	
	/*
	 * 获取异常订单
	*/
	public static function getUnnormalOrders() {
		$result = array();
	
		return $result;
	}
	
	/*
	 * 批量获取物流系统订单状态更新CFF订单状态
	 */
	public static function orderBatchShippedUpdate() {
		$condition = array("os_status"=>4);
		$pageSize = 100;
		$page = 1;
		$orderShipModel = new Order_Model_OrderShip();
		//$orders=$orderShipModel->getByCondition($condition,'*',null,$pageSize,$page);
		$orders=$orderShipModel->getByCondition($condition,'*',null);
		$result = array();
		//while(count($orders)){
			foreach($orders as $order){
				echo $order['orders_code']."\n";
				$obj = new Order_Service_OrderProccess($order['orders_code']);
				$update =  $obj->getIshipStatusUpdateOrder();
				
				if($update){
					$result[]=array(
						'orders_code'=>$order['orders_code'],
						'msg'=>'Update Shipped Success '.date("Y-m-d:H:i:s"),
					);
				}
			}
			//unset($orders);
			//$orders=$orderShipModel->getByCondition($condition,'*',null,$pageSize,$page);
			//$orders = Order_Service_Order::getByCondition($condition,'*',null,$pageSize,$page);
		//}	
		
		return $result;
	}

     /*
      * 批量获取物流系统EPACKET跟踪号，更新order_ship 表 ref_tracking_number
      */
    public static function getIshipRefTrackingNumber() {
        $condition = array("os_status"=>9);
        $pageSize = 100;
        $page = 1;
        $orderShipModel = new Order_Model_OrderShip();
        $orders=$orderShipModel->getByCondition($condition,'*',null);
        $result = array();
        foreach($orders as $order){
            echo $order['orders_code']."\n";
            $obj = new Order_Service_OrderProccess($order['orders_code']);
            $update =  $obj->getIshipUpdateRefTrackingNumber();
            if($update){
                $result[]=array(
                    'orders_code'=>$order['orders_code'],
                    'msg'=>'Update RefTrackingNumber Success '.date("Y-m-d:H:i:s"),
                );
            }
        }
        return $result;
    }
	
	public static function groupByShipMethod($condition=array(),$orderby=array()) {
		$obj = new Order_Model_Order();
		return $obj->groupByShipMethod($condition,$orderby);
	}
	
	public static function getByValue($value,$field='order_id',$type='*'){
        $Obj = new Order_Model_Order();
        return $Obj->getByValue($value,$field,$type);
	}
	
	
	//导出
	public static function csv($orders_codes){
		$Rows_map = array(//中英文对应
				"order_id"=>'订单ID',
				"orders_code"=>'订单号',
				"tracking_number"=>'物流单号',
				"op_code"=>'下架单号',
				"customer_id"=>'客户编号',
				"customer_order_code"=>'客户自定义订单号',
				"warehouse_id"=>'仓库ID',
// 				"consignee_first_name"=>'',
// 				"consignee_last_name"=>'',
// 				"consignee_company"=>'',
				"consignee_country_id"=>'国家',
// 				"consignee_zip"=>'',
// 				"consignee_region"=>'',
// 				"consignee_city"=>'',
// 				"consignee_address1"=>'',
// 				"consignee_address2"=>'',
// 				"consignee_phone"=>'',
// 				"consignee_email"=>'',
				"shipping_method"=>'运输方式',
				"parcel_declared_value"=>'申报价值',
// 				"parcel_contents"=>'',
// 				"parcel_quantity"=>'',
				"orders_status"=>'前台状态',
// 				"process_status"=>'后台状态',
				"process_status_ch"=>'后台状态',
// 				"problem_status"=>'',
// 				"stop_status"=>'',
// 				"import_status"=>'',
// 				"underreview_status"=>'',
				"shipping_fee_estimate"=>'运费',
				"import_time"=>'导入时间',
				"add_time"=>'创建日期',
				"print_time"=>'打印时间',
// 				"submit_time"=>'',
				"ship_date"=>'出货日期',
				"order_stop_date"=>'截单日期',
// 				"delivered_date"=>'收货日期',
// 				"last_modified_time"=>'',
// 				"remark"=>'',
// 				"orders_print_type"=>'',
// 				"pickup_user_id"=>'配货人',
// 				"order_print_id"=>'',
				"pickup_user"=>'配货人',
				
		);
		$Rows = array();
		foreach($orders_codes as $orders_code){
			$Rows[] = self::getByOrdersCode($orders_code);
		}		
		foreach($Rows as $key => $value){
			$Rows[$key]['orders_status']=self::getOrderStatus($value['orders_status']);
			$Rows[$key]['process_status_ch']=self::getProcessStatus($value['process_status']);
			$pickupUser = User_Service_User::getByUserId($value['pickup_user_id']);
			$Rows[$key]['pickup_user'] = '--';
			if($pickupUser){
				$Rows[$key]['pickup_user'] = $pickupUser['name'];
			}
			$orderShip = Order_Service_OrderShip::getLastRowByOrdersCode($value['orders_code']);
			$Rows[$key]['tracking_number'] = '--';
			if($orderShip){
				$Rows[$key]['tracking_number'] = $orderShip['tracking_number'];
			}
		
			$pickupmap  = Order_Service_OrderPickupMap::getByfield("orders_code",$value['orders_code']);
			$Rows[$key]['op_code'] = empty($pickupmap)?"未下架":$pickupmap[0]['op_code'];//下架单号
		
// 			$order_product=Order_Service_Product::getByCondition(array('orders_code'=>$value['orders_code']));
// 			foreach($order_product as $k => $v){
// 				$w_product=Warehouse_Service_Products::getByProductId($v['product_id']);
// 				$order_product[$k]['ws_code']=$w_product['ws_code'];
// 				$category = $service_product->getProductCategory($v['product_id']);
// 				$order_product[$k]['category'] = "";
// 				if($category){
// 					$order_product[$k]['category'] = $category['poc_value'];
// 				}
// 			}
// 			$Rows[$key]['order_product']=$order_product;
			
			$country=Common_Service_Country::getByValue($value['consignee_country_id'],'country_id');
			$Rows[$key]['consignee_country_id']=$country['country_code'];
		}
		$str = "";
		if(count($Rows)>0){
			foreach($Rows_map as $k=>$v){
				$str.=$v.",";
// 				$str.= (isset($Rows_map[$k])&&!empty($Rows_map[$k])?$Rows_map[$k]:$k).",";
			}
			$str = trim($str,',')."\n";
			foreach($Rows as $k=>$v){
				foreach($Rows_map as $k1=>$v1){					
					$str.=$v[$k1].",";
				}
				$str = trim($str,',')."\n";
			}
		}
		
// 		print_r($str);
		return iconv("utf-8","gb2312",$str);
	}
    /*
     * 转问题件
     * param(订单号,原因)
     */
    public static function updateOrdersProblem($ordersCode,$remark=null){
        $lang = Zend_Registry::get('lang');
        $result=array(
            'ask'=>0,
            'msg'=>$lang['operation'].$lang['fail'],
        );
        try{
            $ordersRow=self::getByOrdersCode($ordersCode);
            if(empty($ordersRow)){
                $result['msg']=$lang['order_not_exists'];
                return $result;
            }elseif($ordersRow['problem_status']=='1'){
                $result['msg']=$lang['order_is_problem_order_do_not_repeat'];
                return $result;
            }elseif($ordersRow['orders_status']<3){
                $result['msg']=$lang['order_change_to_problem_fail_reason_order_not_submit'];
                return $result;
            }
            $session = new Zend_Session_Namespace('userAuth');
            $userid=$session->userID;
            $date=date('Y-m-d H:i:s');
            $Rows=array(
                'orders_code'=>$ordersCode,
                'osh_type'=>'Process',
                'osh_statu'=>'0',
                'user_id'=>$userid,
                'osh_create_date'=>$date,
                'osh_remark'=>'problem_status 0 to 1',
                'osh_comments'=>$remark,
                'osh_ip'=>$_SERVER['REMOTE_ADDR'],
            );
            if(self::updateByOrdersCode(array('problem_status'=>'1','last_modified_time'=>$date),$ordersCode)){
                Order_Service_History::create($Rows);
                $result=array(
                    'ask'=>1,
                    'msg'=>$lang['operation'].$lang['success'],
                );
            }
        }catch( Exception $e){
            $result=array(
                'ask'=>0,
                'msg'=>$e->getMessage(),
            );
        }
        return $result;
    }
    

    /**
     *return 
     */
    public  function updateOrderWsCode() {
        $lang = Zend_Registry::get('lang');
    	$condition = array("process_status"=>1,"orders_status"=>3,'ws_code_null'=>'');
    	$orders = self::getByCondition($condition);
    	
    	$msgs = array();
    	$warehouseId = 1;
    	foreach($orders as  $key=>$val){
    		$condition = array("orders_code"=>$val['orders_code']);	
    		$order_products = Order_Service_Product::getByCondition($condition);
    		if(empty($order_products)){
    			$msgs[] = $val['orders_code']." ".$lang['has_no_product']; 
    			continue;	
    		}
    		
    		$order_products = $order_products[0];    
    		$condition = array('product_id'=> $order_products['product_id'],"warehouse_id"=>$warehouseId);		
    		$batchs = Warehouse_Service_ProductsBatch::getByCondition($condition);
    		if(empty($batchs)){
    			$msgs[] = $val['customer_id']."-".$order_products['product_sku']." ".$lang['no_warehouse_batch'];
    			continue;
    		}
    		foreach($batchs as $k=> $v){
    			$condition = array('ws_code'=> $val['ws_code'],"warehouse_id"=>$warehouseId);
    			$shelfs = Warehouse_Service_Shelf::getByCondition($condition,"*","ws_sort desc");
    			if(empty($shelfs)){
    				$msgs[] = $v['ws_code']." ".$lang['not_exists'];
    				continue;
    			}
    			$shelfs = $shelfs[0];
    			$batchs[$k]['ws_sort'] = $shelfs['ws_sort'];    		
    		}
//     		echo __CLASS__;exit;
			usort($batchs, array("Order_Service_OrderProccess","my_sort"));
//     		print_r($batchs[0]);exit;
//     		$orders[$key]['ws_code'] = $batchs[0]['ws_code'];
    		$row = array('ws_code'=>$batchs[0]['ws_code']);
    		self::update($row, $val['order_id']); 
    	}
//     	print_r($msgs);exit;
    	return $msgs;
    }
}